var ws = new WebSocket("ws://" + window.location.host + "/websockettest/");
ws.binaryType = "arraybuffer";

ws.onopen = function () {
    ws.send("I'm client");
};

ws.onmessage = function (evt) {
    var bytes = new Uint8Array(evt.data);
    var data = "";
    var len = bytes.byteLength;
    for (var i = 0; i < len; ++i) {
        data += String.fromCharCode(bytes[i]);
    }
    var img = document.getElementById("target");
    img.src = "data:image/png;base64," + window.btoa(data);
};

ws.onclose = function () {
    alert("Closed");
};

ws.onerror = function (err) {
    alert("Error: " + err);
};

var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

getUserMedia.call(navigator, {
    video: true,
    audio: true
}, function (localMediaStream) {
    video.src = window.URL.createObjectURL(localMediaStream);
    video.onloadedmetadata = function (e) {
        console.log("Label: " + localMediaStream.label);
        console.log("AudioTracks", localMediaStream.getAudioTracks());
        console.log("VideoTracks", localMediaStream.getVideoTracks());
    };
}, function (e) {
    console.log('Reeeejected!', e);
});

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type: mimeString});
}

timer = setInterval(
    function () {
        ctx.drawImage(video, 0, 0, 320, 240);
        var data = canvas.toDataURL('image/jpeg', 1.0);
        newblob = dataURItoBlob(data);
        ws.send(data);
    }, 2);